package ac.github.os.internal.hook

import ac.github.oa.api.OriginAttributeAPI
import ac.github.os.api.central.SkillCentral
import ac.github.os.api.common.DepPlugin
import ac.github.os.internal.core.action.IEntityAction
import ac.github.os.internal.core.config.StringConfig
import ac.github.os.internal.core.config.get
import ac.github.os.internal.core.skill.Coolable
import ac.github.os.internal.core.trigger.EntityTrigger
import ac.github.os.internal.session.Cache
import ac.github.os.internal.session.Session
import org.bukkit.Bukkit
import org.bukkit.entity.LivingEntity
import taboolib.common.platform.Awake
import taboolib.common.platform.function.submit
import java.util.*

@DepPlugin("OriginAttribute")
@Awake
class OriginAttributeAction : IEntityAction {

    override fun onExecute(session: Session, cache: Cache, config: StringConfig) {
        val list = config.get<List<String>>("val", listOf()) ?: return
        val timeout = config.get<Double>("t") ?: return
        val stamp = System.currentTimeMillis() + timeout * 1000
        cache.filterIsEntities().forEach {
            val data = Data(it, list)
            SkillCentral.included(EntityTrigger(it), data, stamp)
            data.send()
        }
    }

    override val namespace: String
        get() = "oa:attr"

    class Data(val livingEntity: LivingEntity, val list: List<String>) : Coolable {

        private val uuid = UUID.randomUUID().toString()

        fun send() {
            val attributeData = OriginAttributeAPI.loadList(list)
            OriginAttributeAPI.setExtra(
                livingEntity.uniqueId,
                uuid,
                attributeData
            )
            OriginAttributeAPI.callUpdate(livingEntity)
        }

        override fun onEnd() {
            OriginAttributeAPI.removeExtra(livingEntity.uniqueId, uuid)
            OriginAttributeAPI.callUpdate(livingEntity)
        }
    }

}
